package com.baidu.baiduyun;

/***************************************************************************
 * 
 * Copyright (c) 2012 Baidu.com, Inc. All Rights Reserved 
 * 
 **************************************************************************/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.baidu.inf.iis.bcs.BaiduBCS;
import com.baidu.inf.iis.bcs.auth.BCSCredentials;
import com.baidu.inf.iis.bcs.auth.BCSSignCondition;
import com.baidu.inf.iis.bcs.http.HttpMethodName;
import com.baidu.inf.iis.bcs.model.BCSClientException;
import com.baidu.inf.iis.bcs.model.BCSServiceException;
import com.baidu.inf.iis.bcs.model.BucketSummary;
import com.baidu.inf.iis.bcs.model.Empty;
import com.baidu.inf.iis.bcs.model.ObjectListing;
import com.baidu.inf.iis.bcs.model.ObjectMetadata;
import com.baidu.inf.iis.bcs.model.ObjectSummary;
import com.baidu.inf.iis.bcs.model.Resource;
import com.baidu.inf.iis.bcs.model.SuperfileSubObject;
import com.baidu.inf.iis.bcs.model.X_BS_ACL;
import com.baidu.inf.iis.bcs.policy.Policy;
import com.baidu.inf.iis.bcs.policy.PolicyAction;
import com.baidu.inf.iis.bcs.policy.PolicyEffect;
import com.baidu.inf.iis.bcs.policy.Statement;
import com.baidu.inf.iis.bcs.request.CreateBucketRequest;
import com.baidu.inf.iis.bcs.request.GenerateUrlRequest;
import com.baidu.inf.iis.bcs.request.GetObjectRequest;
import com.baidu.inf.iis.bcs.request.ListBucketRequest;
import com.baidu.inf.iis.bcs.request.ListObjectRequest;
import com.baidu.inf.iis.bcs.request.PutObjectRequest;
import com.baidu.inf.iis.bcs.request.PutSuperfileRequest;
import com.baidu.inf.iis.bcs.response.BaiduBCSResponse;

@SuppressWarnings("unused")
public class Baidu {
	private static final Log log = LogFactory.getLog(Baidu.class);
	// ----------------------------------------
	static String host = "bcs.duapp.com";
	static String accessKey = "aFCvApG0HCfeH6SfQsV31yBi";
	static String secretKey = "6ONfNLzzjTGi0LosSVndvakXgCfm4gO5";
	static String bucket = "pluto-coding";

	// ----------------------------------------

	private static BaiduBCS baiduBCS = null;
	static {
		createBaiduBCS();
	}

	public static BaiduBCS getBaiduBCS() {
		if (baiduBCS == null) {
			createBaiduBCS();
		}

		return baiduBCS;
	}

	private static void createBaiduBCS() {
		BCSCredentials credentials = new BCSCredentials(accessKey, secretKey);
		baiduBCS = new BaiduBCS(credentials, host);
		baiduBCS.setDefaultEncoding("UTF-8");
	}

	/**
	 * @param args
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	public static void main(String[] args) throws URISyntaxException, IOException {
		try {
			// -------------bucket-------------
			// listBucket();
			// createBucket(getBaiduBCS());
			// deleteBucket(getBaiduBCS());
			getBucketPolicy();
			// putBucketPolicyByPolicy(getBaiduBCS());
			// putBucketPolicyByX_BS_ACL(getBaiduBCS(), X_BS_ACL.PublicControl);
			// listObject();
			// ------------object-------------
			// putObjectByFile(getBaiduBCS());
			// putObjectByInputStream(getBaiduBCS());
			// getObjectWithDestFile(getBaiduBCS());
			// putSuperfile(getBaiduBCS());
			// deleteObject(getBaiduBCS());
			// getObjectMetadata(getBaiduBCS());
			// setObjectMetadata(getBaiduBCS());
			// copyObject(getBaiduBCS(), bucket, object + "_copy" +
			// (System.currentTimeMillis()));
			// getObjectPolicy(getBaiduBCS());
			// putObjectPolicyByPolicy(getBaiduBCS());
			// putObjectPolicyByX_BS_ACL(getBaiduBCS(), X_BS_ACL.PublicControl);

			// ------------common------------------
			// generateUrl(getBaiduBCS(), "xls");
		} catch (BCSServiceException e) {
			log.warn("Bcs return:" + e.getBcsErrorCode() + ", " + e.getBcsErrorMessage() + ", RequestId=" + e.getRequestId());
		} catch (BCSClientException e) {
			e.printStackTrace();
		}
	}

	public static String generateUrl(String fileName) {
		GenerateUrlRequest generateUrlRequest = new GenerateUrlRequest(HttpMethodName.GET, bucket, "/" + fileName);
		generateUrlRequest.setBcsSignCondition(new BCSSignCondition());
		generateUrlRequest.getBcsSignCondition().setIp("1.1.1.1");
		generateUrlRequest.getBcsSignCondition().setTime(123455L);
		generateUrlRequest.getBcsSignCondition().setSize(123455L);
		return getBaiduBCS().generateUrl(generateUrlRequest);
	}

	public static void copyObject(String destBucket, String destObject, String fileName) {
		fileName = "/" + fileName;
		ObjectMetadata objectMetadata = new ObjectMetadata();
		objectMetadata.setContentType("image/jpeg");
		getBaiduBCS().copyObject(new Resource(bucket, fileName), new Resource(destBucket, destObject), objectMetadata);
		getBaiduBCS().copyObject(new Resource(bucket, fileName), new Resource(destBucket, destObject), null);
		getBaiduBCS().copyObject(new Resource(bucket, fileName), new Resource(destBucket, destObject));
	}

	private static void createBucket() {
		// baiduBCS.createBucket(bucket);
		getBaiduBCS().createBucket(new CreateBucketRequest(bucket, X_BS_ACL.PublicRead));
	}

	private static void deleteBucket() {
		getBaiduBCS().deleteBucket(bucket);
	}

	public static Empty deleteObject(String fileName) {
		Empty result = getBaiduBCS().deleteObject(bucket, "/" + fileName).getResult();
		log.info(result);
		return result;
	}

	private static BaiduBCSResponse<Policy> getBucketPolicy() {
		BaiduBCSResponse<Policy> response = getBaiduBCS().getBucketPolicy(bucket);

		log.info("After analyze: " + response.getResult().toJson());
		log.info("Origianal str: " + response.getResult().getOriginalJsonStr());
		return response;
	}

	public static ObjectMetadata getObjectMetadata(String fileName) {
		ObjectMetadata objectMetadata = getBaiduBCS().getObjectMetadata(bucket, "/" + fileName).getResult();
		log.info(objectMetadata);
		return objectMetadata;
	}

	private static BaiduBCSResponse<Policy> getObjectPolicy(String fileName) {
		BaiduBCSResponse<Policy> response = getBaiduBCS().getObjectPolicy(bucket, "/" + fileName);
		log.info("After analyze: " + response.getResult().toJson());
		log.info("Origianal str: " + response.getResult().getOriginalJsonStr());
		return response;
	}

	private static void getObjectWithDestFile(String fileName, File file) {
		GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, "/" + fileName);
		getBaiduBCS().getObject(getObjectRequest, file);
	}

	private static List<BucketSummary> listBucket() {
		ListBucketRequest listBucketRequest = new ListBucketRequest();
		BaiduBCSResponse<List<BucketSummary>> response = getBaiduBCS().listBucket(listBucketRequest);

		if (log.isInfoEnabled()) {
			for (BucketSummary bucket : response.getResult()) {
				log.info(bucket);
			}
		}

		return response.getResult();
	}

	private static void listObject() {
		ListObjectRequest listObjectRequest = new ListObjectRequest(bucket);
		listObjectRequest.setStart(0);
		listObjectRequest.setLimit(20);
		// ------------------by dir
		{
			// prefix must start with '/' and end with '/'
			// listObjectRequest.setPrefix("/1/");
			// listObjectRequest.setListModel(2);
		}
		// ------------------only object
		{
			// prefix must start with '/'
			// listObjectRequest.setPrefix("/1/");
		}
		BaiduBCSResponse<ObjectListing> response = getBaiduBCS().listObject(listObjectRequest);
		log.info("we get [" + response.getResult().getObjectSummaries().size() + "] object record.");
		for (ObjectSummary os : response.getResult().getObjectSummaries()) {
			log.info(os.toString());
		}
	}

	private static void putBucketPolicyByPolicy() {
		Policy policy = new Policy();
		Statement st1 = new Statement();
		st1.addAction(PolicyAction.all).addAction(PolicyAction.get_object);
		st1.addUser("zhengkan").addUser("zhangyong01");
		st1.addResource(bucket + "/111").addResource(bucket + "/111");
		st1.setEffect(PolicyEffect.allow);
		policy.addStatements(st1);
		getBaiduBCS().putBucketPolicy(bucket, policy);
	}

	private static BaiduBCSResponse<Empty> putBucketPolicyByX_BS_ACL(X_BS_ACL acl) {
		return getBaiduBCS().putBucketPolicy(bucket, acl);
	}

	public static ObjectMetadata putObjectByFile(String fileName, File file) {
		PutObjectRequest request = new PutObjectRequest(bucket, "/" + fileName, file);
		request.setAcl(X_BS_ACL.PublicRead);
		ObjectMetadata metadata = new ObjectMetadata();

		// metadata.setContentType("text/html");
		request.setMetadata(metadata);
		BaiduBCSResponse<ObjectMetadata> response = getBaiduBCS().putObject(request);
		ObjectMetadata objectMetadata = response.getResult();
		log.info("x-bs-request-id: " + response.getRequestId());
		log.info(objectMetadata);
		return objectMetadata;
	}

	public static void putObjectByInputStream(String fileName, File file) throws FileNotFoundException {
		// File file = createSampleFile();
		InputStream fileContent = new FileInputStream(file);
		ObjectMetadata objectMetadata = new ObjectMetadata();
		objectMetadata.setContentType("text/html");
		objectMetadata.setContentLength(file.length());
		PutObjectRequest request = new PutObjectRequest(bucket, "/" + fileName, fileContent, objectMetadata);
		ObjectMetadata result = getBaiduBCS().putObject(request).getResult();
		log.info(result);
	}

	private static void putObjectPolicyByPolicy(String fileName) {
		Policy policy = new Policy();
		Statement st1 = new Statement();
		st1.addAction(PolicyAction.all).addAction(PolicyAction.get_object);
		st1.addUser("zhengkan").addUser("zhangyong01");
		st1.addResource(bucket + "/" + fileName).addResource(bucket + "/" + fileName);
		st1.setEffect(PolicyEffect.allow);
		policy.addStatements(st1);
		getBaiduBCS().putObjectPolicy(bucket, "/" + fileName, policy);
	}

	private static void putObjectPolicyByX_BS_ACL(X_BS_ACL acl, String fileName) {
		getBaiduBCS().putObjectPolicy(bucket, "/" + fileName, acl);
	}

	public static void putSuperfile(String fileName, File file) {
		List<SuperfileSubObject> subObjectList = new ArrayList<SuperfileSubObject>();
		// 0
		BaiduBCSResponse<ObjectMetadata> response1 = getBaiduBCS().putObject(bucket, "/" + fileName + "_part0", file);
		subObjectList.add(new SuperfileSubObject(bucket, "/" + fileName + "_part0", response1.getResult().getETag()));
		// 1
		BaiduBCSResponse<ObjectMetadata> response2 = getBaiduBCS().putObject(bucket, "/" + fileName + "_part1", file);
		subObjectList.add(new SuperfileSubObject(bucket, "/" + fileName + "_part1", response2.getResult().getETag()));
		// put superfile
		PutSuperfileRequest request = new PutSuperfileRequest(bucket, "/" + fileName + "_superfile", subObjectList);
		BaiduBCSResponse<ObjectMetadata> response = getBaiduBCS().putSuperfile(request);
		ObjectMetadata objectMetadata = response.getResult();
		log.info("x-bs-request-id: " + response.getRequestId());
		log.info(objectMetadata);
	}

	public static void setObjectMetadata(String fileName) {
		ObjectMetadata objectMetadata = new ObjectMetadata();
		objectMetadata.setContentType("text/html12");
		getBaiduBCS().setObjectMetadata(bucket, "/" + fileName, objectMetadata);
	}

	private static File createSampleFile() {
		try {
			File file = File.createTempFile("java-sdk-", ".txt");
			file.deleteOnExit();

			Writer writer = new OutputStreamWriter(new FileOutputStream(file));
			writer.write("01234567890123456789\n");
			writer.write("01234567890123456789\n");
			writer.write("01234567890123456789\n");
			writer.write("01234567890123456789\n");
			writer.write("01234567890123456789\n");
			writer.close();

			return file;
		} catch (IOException e) {
			log.error("tmp file create failed.");
			return null;
		}
	}
}